package com.cspg.design.ui.pointDevice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableRow;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bumptech.glide.Glide;
import com.cspg.design.CSPGApplication;
import com.cspg.design.CheckPermissionsActivity;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.modelLibrary.TowerLibrary;
import com.cspg.design.bean.modelLibrary.TransformerLibrary;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.common.Constant;
import com.cspg.design.compressor.CompressServiceParam;
import com.cspg.design.compressor.Constanse;
import com.cspg.design.compressor.LGImgCompressor;
import com.cspg.design.compressor.LGImgCompressorIntentService;
import com.cspg.design.compressor.LGImgCompressorService;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.dao.gen.TowerLibraryDao;
import com.cspg.design.dao.gen.TransformerLibraryDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.model.PointDeviceModel;
import com.cspg.design.presenter.UploadFilePresenter;
import com.cspg.design.request.PointDevice;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.ToastUtils;
import com.wildma.pictureselector.PictureBean;
import com.wildma.pictureselector.PictureSelector;

import org.greenrobot.greendao.rx.RxQuery;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class PointDeviceActivity extends CheckPermissionsActivity {
    public static final String TAG = "PictureSelector";
    private EditText et_point_name; //本桩位
    private EditText et_pre_point_name;//前桩位
    private EditText et_longitude;//经度
    private EditText et_latitude;//纬度
    private EditText et_status;//状态
    private EditText et_typical;//典型方案
    private EditText et_tower_model;//杆型代码
    private EditText et_tower_height;//杆高
    private EditText et_tip_diameter;//梢径
    private EditText et_dev_material_quality;//设备材质
    private EditText et_distance;//档距
    private EditText et_corner_degree;//转角度数
    private EditText et_trans_pole_model ; // 变压器杆塔型号
    private ImageView iv_far_pic;//远景图
    private ImageView iv_near_pic;//近景图
    private ImageView iv_pole_pic;//杆塔号

    private TableRow tr_trans_pole_model; //变压器杆塔

    private ImageView iv_review;//浏览图片
    private LinearLayout ll_review;

    private Uri far_pic_uri;
    private Uri near_pic_uri;
    private Uri pole_pic_uri;

    private String far_pic_path;
    private String near_pic_path;
    private String pole_pic_path;

    private int mClickCode = 0;

    private DaoSession daoSession;
    private RxQuery<PointDeviceBean> pointDeviceBeanRxQuery;

    private final PointDeviceModel pointDeviceModel = new PointDeviceModel();

    private String[] poleModel;

    private UploadFilePresenter uploadFilePresenter;

    private long serviceStartTime;
    private CompressingReciver reciver;

    private EditText et_polyline_end_point_name; //本桩位
    private EditText et_polyline_pre_point_name;//前桩位
    private EditText et_polyline_status;//状态
    private EditText et_polyline_distance;//档距
    private EditText et_polyline_wire_model;//导向型号
    private EditText et_polyline_circuits_number;//回路数
    private EditText et_polyline_margin;//裕度
    private EditText et_polyline_cross_section;//截面积
    private EditText et_polyline_wire_material_quality;//导线材质

    private PolylineDeviceBean polyline;
    private String[] wireModel;
    private Button btn_polyline_save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_device);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        ActionBarUtil.setActionBar(this, R.string.point_device_title);

        reciver = new CompressingReciver();
        IntentFilter intentFilter = new IntentFilter(Constanse.ACTION_COMPRESS_BROADCAST);
        registerReceiver(reciver, intentFilter);

        et_point_name = findViewById(R.id.et_point_name);
        et_pre_point_name = findViewById(R.id.et_pre_point_name);
        et_longitude = findViewById(R.id.et_longitude);
        et_latitude = findViewById(R.id.et_latitude);
        et_status = findViewById(R.id.et_status);
        et_typical = findViewById(R.id.et_typical);
        et_tower_model = findViewById(R.id.et_tower_model);
        et_tower_height = findViewById(R.id.et_tower_height);
        et_tip_diameter = findViewById(R.id.et_tip_diameter);
        et_dev_material_quality = findViewById(R.id.et_dev_material_quality);
        et_distance = findViewById(R.id.et_distance);
        et_corner_degree = findViewById(R.id.et_corner_degree);
        iv_review = findViewById(R.id.iv_review);
        ll_review = findViewById(R.id.ll_review);
        et_trans_pole_model = findViewById(R.id.et_trans_pole_model);
        tr_trans_pole_model = findViewById(R.id.tr_trans_pole_model);
        Button btn_review = findViewById(R.id.btn_review_change);
        btn_review.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(PointDeviceActivity.this, mClickCode)
                        .selectPicture(false);
            }
        });

        iv_review.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ll_review.getVisibility() == View.VISIBLE) {
                    ll_review.setVisibility(View.GONE);
                }
            }
        });
        iv_far_pic = findViewById(R.id.iv_far_img);
        iv_far_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (far_pic_uri == null) {
                    PictureSelector.create(PointDeviceActivity.this, 0x01)
                            .selectPicture(false);
                } else {
                    mClickCode = 0x01;
//                    iv_review.setImageURI(far_pic_uri);
                    ll_review.setVisibility(View.VISIBLE);
                    Glide.with(PointDeviceActivity.this)
                            .load(far_pic_uri.toString())
                            .placeholder(R.drawable.ic_add_img)
                            .error(R.drawable.ic_error_image)
                            .into(iv_review);
                }
            }
        });
        iv_near_pic = findViewById(R.id.iv_near_img);
        iv_near_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (near_pic_uri == null) {
                    PictureSelector.create(PointDeviceActivity.this, 0x02)
                            .selectPicture(false);
                } else {
                    mClickCode = 0x02;
//                    iv_review.setImageURI(near_pic_uri);
                    ll_review.setVisibility(View.VISIBLE);
                    Glide.with(PointDeviceActivity.this)
                            .load(near_pic_uri.toString())
                            .placeholder(R.drawable.ic_add_img)
                            .error(R.drawable.ic_error_image)
                            .into(iv_review);
                }
            }
        });

        iv_pole_pic = findViewById(R.id.iv_pole_num);
        iv_pole_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pole_pic_uri == null) {
                    PictureSelector.create(PointDeviceActivity.this, 0x03)
                            .selectPicture(false);
                } else {
                    mClickCode = 0x03;
//                    iv_review.setImageURI(pole_pic_uri);
                    ll_review.setVisibility(View.VISIBLE);
                    Glide.with(PointDeviceActivity.this)
                            .load(pole_pic_uri.toString())
                            .placeholder(R.drawable.ic_add_img)
                            .error(R.drawable.ic_error_image)
                            .into(iv_review);
                }
            }
        });

        String[] status = new String[]{"新增", "原有", "换装", "拆除"};
        et_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertListDialog.ListBuilder(PointDeviceActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请选择设备状态")
                        .setIcon(R.drawable.ic_info)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setItems(status, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                et_status.setText(status[which]);
                            }
                        }).create().show();

            }
        });
        et_tower_model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (  pointDeviceModel.getCurrentPointDevice().getPointType() == 3) {
                    showTransformAlertDialog();
                }
                else {
                    new AlertListDialog.ListBuilder(PointDeviceActivity.this)
                            .setDividerColorRes(R.color.color_divider)
                            .setDividerHeightRes(R.dimen.dp1)
                            .setTitle("请选择设备型号")
                            .setIcon(R.drawable.ic_info)
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setItems(poleModel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    et_tower_model.setText(poleModel[which]);
                                }
                            }).create().show();

                }
            }
        });
        Button btn_save = findViewById(R.id.btn_point_device_save);
        if (UserInfo.getInstance().role.contains("设计"))
        {
            btn_save.setVisibility(View.GONE);
        }
        btn_save.setOnClickListener(v -> {
            PointDeviceBean pointDeviceBean = pointDeviceModel.getCurrentPointDevice();
            pointDeviceBean.setPointName(et_point_name.getText().toString());
            String label = et_status.getText().toString();
            if (label.equals("新增")) {
                pointDeviceBean.setPointStatue(1);
            } else if (label.equals("原有")) {
                pointDeviceBean.setPointStatue(2);
            } else if (label.equals("换装")) {
                pointDeviceBean.setPointStatue(3);
            } else if (label.equals("拆除")) {
                pointDeviceBean.setPointStatue(4);
            }
            if (pointDeviceBean.getPointType() == 3)
            {
                pointDeviceBean.setPointModel(et_trans_pole_model.getText().toString());
            }
            else
            {
                pointDeviceBean.setPointModel(et_tower_model.getText().toString());
            }
            updateData(pointDeviceBean);
        });

        et_polyline_status = findViewById(R.id.et_polyline_status);
        et_polyline_distance = findViewById(R.id.et_polyline_distance);
        et_polyline_end_point_name = findViewById(R.id.et_polyline_end_point_name);
        et_polyline_pre_point_name = findViewById(R.id.et_polyline_pre_point_name);
        et_polyline_wire_model = findViewById(R.id.et_polyline_wire_model);
        et_polyline_circuits_number = findViewById(R.id.et_polyline_circuits_number);
        et_polyline_margin = findViewById(R.id.et_polyline_margin);
        et_polyline_cross_section = findViewById(R.id.et_polyline_cross_section);
        et_polyline_wire_material_quality = findViewById(R.id.et_polyline_wire_material_quality);
        et_polyline_wire_model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertListDialog.ListBuilder(PointDeviceActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请选择设备状态")
                        .setIcon(R.drawable.ic_info)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setItems(wireModel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                et_polyline_wire_model.setText(wireModel[which]);
                            }
                        }).create().show();

            }
        });
        btn_polyline_save = findViewById(R.id.btn_polyline_device_save);
        if (UserInfo.getInstance().role.contains("设计"))
        {
            btn_save.setVisibility(View.GONE);
        }
        btn_polyline_save.setOnClickListener(v -> {

            PointDeviceBean pointDeviceBean = pointDeviceModel.getCurrentPointDevice();
            pointDeviceBean.setPointName(et_point_name.getText().toString());
            String label = et_status.getText().toString();
            if (label.equals("新增")) {
                pointDeviceBean.setPointStatue(1);
            } else if (label.equals("原有")) {
                pointDeviceBean.setPointStatue(2);
            } else if (label.equals("换装")) {
                pointDeviceBean.setPointStatue(3);
            } else if (label.equals("拆除")) {
                pointDeviceBean.setPointStatue(4);
            }
//            pointDeviceBean.setPointModel(et_tower_model.getText().toString());
            if (pointDeviceBean.getPointType() == 3)
            {
                pointDeviceBean.setPointModel(et_trans_pole_model.getText().toString());
            }
            else
            {
                pointDeviceBean.setPointModel(et_tower_model.getText().toString());
            }
            updateData(pointDeviceBean);
            if (polyline != null && polyline.getPolylineUuid() != null)
            {
                polyline.setPolylineModel(et_polyline_wire_model.getText().toString());
                polyline.setCircuitsNum(et_polyline_circuits_number.getText().toString().trim());
                polyline.setMargin(et_polyline_margin.getText().toString().trim());
                updatePolylineData(polyline);
            }
        });

        daoSession = ((CSPGApplication) getApplication()).getDaoSession();
        initData();
        uploadFilePresenter = new UploadFilePresenter(this);
    }

    private void initData() {
        String uuid = getIntent().getStringExtra("uuid");
        if (null == uuid) {
            return;
        }
        queryPointDeviceBeanByUUID(uuid);

    }

    private void queryPointDeviceBeanByUUID(String uuid) {
        pointDeviceBeanRxQuery = daoSession.getPointDeviceBeanDao()
                .queryBuilder()
                .where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid))
                .rx();
        pointDeviceBeanRxQuery.unique().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PointDeviceBean>() {
            @Override
            public void call(PointDeviceBean pointDeviceBean) {
                pointDeviceModel.setCurrentPointDevice(pointDeviceBean);
                ProjectBean projectBean = daoSession.getProjectBeanDao()
                        .queryBuilder()
                        .where(ProjectBeanDao.Properties.ProjectId.eq(pointDeviceBean.getProjectId()))
                        .unique();
                String schemeType = projectBean.getSchemaType();
                String schemeName = projectBean.getSchemeName();
                if (schemeType.equals("low")) {
                    List<MyLowVoltageSchemeBean> myLowVoltageSchemeBeans = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                            .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                    MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                            .list();
                    if (myLowVoltageSchemeBeans == null || myLowVoltageSchemeBeans.size() == 0)
                    {
                        return;
                    }
                    else {
                        MyLowVoltageSchemeBean myLowVoltageSchemeBean = myLowVoltageSchemeBeans.get(0);
                        String pole = myLowVoltageSchemeBean.getTypicalDesignModel();
                        if (pole != null && !pole.isEmpty()) {
                            poleModel = pole.split("&");
                        }
                    }
                } else if (schemeType.equals("high")) {
                    List<MyHighVoltageSchemeBean> myHighVoltageSchemeBeans = daoSession.getMyHighVoltageSchemeBeanDao().queryBuilder()
                            .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                    MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                            .list();
                    if (myHighVoltageSchemeBeans ==null || myHighVoltageSchemeBeans.size() == 0 )
                    {
                        return;
                    }
                    else {
                        MyHighVoltageSchemeBean myHighVoltageSchemeBean = myHighVoltageSchemeBeans.get(0);
                        String pole = myHighVoltageSchemeBean.getTypicalDesignModel();
                        if (pole != null && !pole.isEmpty()) {
                            poleModel = pole.split("&");
                        }
                    }
                }
                if (pointDeviceBean.getPrePointUUID() != null)
                {
                    queryPointDeviceBeanByID(pointDeviceBean.getPrePointUUID());
                }
                List<PolylineDeviceBean> polylineDeviceBeans =  daoSession.getPolylineDeviceBeanDao().queryBuilder().where(PolylineDeviceBeanDao.Properties.EndPointUUID.eq(uuid)).list();
                if (polylineDeviceBeans.size() > 1)
                {
                    String prePointUUID = pointDeviceBean.getPrePointUUID();
                    if (prePointUUID != null)
                    {
                        for (PolylineDeviceBean polylineDeviceBean : polylineDeviceBeans){
                            String startPointUUID = polylineDeviceBean.getStartPointUUID();
                            if (prePointUUID.equals(startPointUUID))
                            {
                                initPolylineData(polylineDeviceBean.getPolylineUuid());
                            }
                        }
                    }
                }
                else if (polylineDeviceBeans.size() == 1)
                {
                    initPolylineData(polylineDeviceBeans.get(0).getPolylineUuid());
                }
//                else
//                {
//                    btn_polyline_save.setClickable(false);
//                    btn_polyline_save.setBackgroundColor(Color.GRAY);
//
//                }
                initUI();
            }
        });
    }

    private void queryPointDeviceBeanByID(String uuid) {
//        pointDeviceBeanRxQuery = daoSession.getPointDeviceBeanDao()
//                .queryBuilder()
//                .where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid))
//                .rx();
//        pointDeviceBeanRxQuery.unique().observeOn(AndroidSchedulers.mainThread()).subscribe(pointDeviceBean -> {
//            if (pointDeviceBean != null) {
//                pointDeviceModel.setPrePointDevice(pointDeviceBean);
//            }
//
//        });
        PointDeviceBean pointDeviceBean = daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.PointUuid.eq(uuid)).unique();
        if (pointDeviceBean != null) {
                pointDeviceModel.setPrePointDevice(pointDeviceBean);
            }
    }

    private void initUI() {
        et_point_name.setText(pointDeviceModel.getCurrentPointDevice().getPointName());
        if (pointDeviceModel.getPrePointDevice() != null) {
            et_pre_point_name.setText(pointDeviceModel.getPrePointDevice().getPointName());
        } else {
            et_pre_point_name.setText("");
        }
        et_longitude.setText(String.valueOf(pointDeviceModel.getCurrentPointDevice().getLongitude()));
        et_latitude.setText(String.valueOf(pointDeviceModel.getCurrentPointDevice().getLatitude()));
        switch (pointDeviceModel.getCurrentPointDevice().getPointStatue()) {
            case 1:
                et_status.setText("新增");
                break;
            case 2:
                et_status.setText("原有");
                break;
            case 3:
                et_status.setText("换装");
                break;
            case 4:
                et_status.setText("拆除");
                break;
        }
        et_typical.setText(pointDeviceModel.getCurrentPointDevice().getSchemaName());
        int deviceType = pointDeviceModel.getCurrentPointDevice().getPointType();
        if (deviceType != 3){
            et_tower_model.setText(pointDeviceModel.getCurrentPointDevice().getPointModel());
        }
        if (deviceType == 1) {
            List<TowerLibrary> towerLibrarys = daoSession.getTowerLibraryDao()
                    .queryBuilder()
                    .where(TowerLibraryDao.Properties.PoleModel.eq(pointDeviceModel.getCurrentPointDevice().getPointModel()))
                    .list();
            if (towerLibrarys != null && towerLibrarys.size() > 0){
                TowerLibrary towerLibrary = towerLibrarys.get(0);
                if (towerLibrary != null) {
                    et_tower_height.setText(towerLibrary.getPoleHeight());
                    et_tip_diameter.setText(towerLibrary.getTipDiameter());
                    et_dev_material_quality.setText(towerLibrary.getWireQuality());
                    et_distance.setText(towerLibrary.getDistance());
                    et_corner_degree.setText(towerLibrary.getMiniCornerDegree() + "~"+towerLibrary.getMaxCornerDegree());
                }
            }
        } else if (deviceType == 3) {
            if (pointDeviceModel.getCurrentPointDevice().getPointModel()  == null)
            {
                return;
            }
            List<TransformerLibrary> transformerLibraries = daoSession.getTransformerLibraryDao()
                    .queryBuilder()
                    .where(TransformerLibraryDao.Properties.PoleModel.eq(pointDeviceModel.getCurrentPointDevice().getPointModel()))
                    .list();
            if (transformerLibraries != null && transformerLibraries.size() > 0)
            {
                TransformerLibrary transformerLibrary = transformerLibraries.get(0);
                tr_trans_pole_model.setVisibility(View.VISIBLE);
                et_tower_model.setText(transformerLibrary.getTransformerModel());
                et_trans_pole_model.setText(pointDeviceModel.getCurrentPointDevice().getPointModel());
            }
        }
        far_pic_path = pointDeviceModel.getCurrentPointDevice().getFarImage();
        if (far_pic_path != null)
        {
            far_pic_uri = Uri.parse(Constant.FILEHost+ far_pic_path);
            Glide.with(this)
                .load(Constant.FILEHost+ far_pic_path)
                .placeholder(R.drawable.ic_add_img)
                .error(R.drawable.ic_error_image)
                .into(iv_far_pic);

        }
        near_pic_path = pointDeviceModel.getCurrentPointDevice().getNearImage();
        if (near_pic_path != null)
        {
            near_pic_uri = Uri.parse(Constant.FILEHost+ near_pic_path);
            Glide.with(this)
                .load(Constant.FILEHost+ near_pic_path)
                .placeholder(R.drawable.ic_add_img)
                .error(R.drawable.ic_error_image)
                .into(iv_near_pic);
        }
        pole_pic_path =  pointDeviceModel.getCurrentPointDevice().getPoleImage();
        if (pole_pic_path != null)
        {
            pole_pic_uri = Uri.parse(Constant.FILEHost+ pole_pic_path);
            Glide.with(this)
                .load(Constant.FILEHost+ pole_pic_path)
                .placeholder(R.drawable.ic_add_img)
                .error(R.drawable.ic_error_image)
                .into(iv_pole_pic);

        }

    }

    private void initPolylineData(String uuid) {
        if (uuid != null && !uuid.isEmpty()) {
            daoSession.getPolylineDeviceBeanDao()
                    .queryBuilder()
                    .where(PolylineDeviceBeanDao.Properties.PolylineUuid.eq(uuid))
                    .rx()
                    .unique()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<PolylineDeviceBean>() {
                        @Override
                        public void call(PolylineDeviceBean polylineDeviceBean) {
                            if (polylineDeviceBean == null) {
                                return;
                            }
                            polyline = polylineDeviceBean;
                            et_polyline_wire_model.setText(polylineDeviceBean.getPolylineModel());
                            String startPointUUID = polylineDeviceBean.getStartPointUUID();
                            String endPointUUID = polylineDeviceBean.getEndPointUUID();
                            PointDeviceBean startPointDeviceBean = daoSession.getPointDeviceBeanDao()
                                    .queryBuilder()
                                    .where(PointDeviceBeanDao.Properties.PointUuid.eq(startPointUUID))
                                    .unique();
                            PointDeviceBean endPointDeviceBean = daoSession.getPointDeviceBeanDao()
                                    .queryBuilder()
                                    .where(PointDeviceBeanDao.Properties.PointUuid.eq(endPointUUID))
                                    .unique();
                            if (startPointDeviceBean != null) {
                                et_polyline_pre_point_name.setText(startPointDeviceBean.getPointName());
                            }
                            if (endPointDeviceBean != null) {
                                et_polyline_end_point_name.setText(endPointDeviceBean.getPointName());
                                int status = endPointDeviceBean.getPointStatue();
                                String label = "";
                                switch (status) {
                                    case 1:
                                        label = "新增";
                                        break;
                                    case 2:
                                        label = "利旧";
                                        break;
                                }
                                et_polyline_status.setText(label);
                            }
                            List<WireLibrary> wireLibrarys = daoSession
                                    .getWireLibraryDao()
                                    .queryBuilder()
                                    .where(WireLibraryDao.Properties.WireModel.eq(polylineDeviceBean.getPolylineModel()))
                                    .list();
                            WireLibrary wireLibrary = wireLibrarys.size() > 0 ? wireLibrarys.get(0) : null;
                            if (wireLibrary != null) {
                                et_polyline_wire_material_quality.setText(wireLibrary.getWireQuality());
                                et_polyline_cross_section.setText(wireLibrary.getWireCrossSection());
                            }
                            Double length = DistanceUtil.getDistance(
                                    new LatLng(startPointDeviceBean.getLatitude(), startPointDeviceBean.getLongitude()),
                                    new LatLng(endPointDeviceBean.getLatitude(), endPointDeviceBean.getLongitude()));
                            length = new BigDecimal(length).setScale(2, RoundingMode.UP).doubleValue();
                            et_polyline_distance.setText(String.valueOf(length));
                            ProjectBean projectBean = daoSession.getProjectBeanDao()
                                    .queryBuilder()
                                    .where(ProjectBeanDao.Properties.ProjectId.eq(polyline.getProjectId()))
                                    .unique();
                            String schemeType = projectBean.getSchemaType();
                            String schemeName = projectBean.getSchemeName();
                            if (schemeType.equals("low")) {
                                MyLowVoltageSchemeBean myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                                        .unique();
                                String wire380 = myLowVoltageSchemeBean.getWireModel380V();
                                String wire220 = myLowVoltageSchemeBean.getWireModel220V();
                                if (wire220 != null && !wire220.isEmpty() && wire380 != null && !wire380.isEmpty()) {
                                    wireModel = new String[2];
                                    wireModel[0] = wire380;
                                    wireModel[1] = wire220;
                                } else if (wire380 == null || wire380.isEmpty()) {
                                    wireModel = new String[1];
                                    wireModel[0] = wire220;
                                } else if (wire220 == null || wire220.isEmpty()) {
                                    wireModel = new String[1];
                                    wireModel[0] = wire380;
                                }
                            } else if (schemeType.equals("high")) {
                                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession.getMyHighVoltageSchemeBeanDao().queryBuilder()
                                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                                        .unique();
                                String model = myHighVoltageSchemeBean.getWireModel();
                                wireModel = new String[1];
                                wireModel[0] = model;
                            }
                        }
                    });
        }
    }

    private void updateData(PointDeviceBean pointDeviceBean) {
        List<File> pathList = new ArrayList<>();
        List<String> imgFlag = new ArrayList<>();
        if (far_pic_path == null && pointDeviceBean.getPointType() == 2  )
        {
            ToastUtils.toast(this,"请选择远景图....");
        }
        else if (near_pic_path == null && pointDeviceBean.getPointType() == 2)
        {
            ToastUtils.toast(this,"请选择近景图.....");
        }
        else if (pole_pic_path == null && pointDeviceBean.getPointType() == 2)
        {
            ToastUtils.toast(this,"请添加杆塔号牌照片.....");
        }
        else
        {
            if (far_pic_path != null && far_pic_path != pointDeviceBean.getFarImage())
            {
                pathList.add(new File(far_pic_path));
                imgFlag.add("far");
            }
            if (near_pic_path != null && near_pic_path != pointDeviceBean.getNearImage())
            {
                pathList.add(new File(near_pic_path));
                imgFlag.add("near");
            }
            if (pole_pic_path != null && pole_pic_path != pointDeviceBean.getPoleImage())
            {
                pathList.add(new File(pole_pic_path));
                imgFlag.add("pole");
            }
        }
        if (pathList.size() > 0)
        {
            uploadFilePresenter.uploadMultipartBodyFile(pathList,pointDeviceBean, imgFlag);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == (0x01)) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                Log.i(TAG, "是否裁剪: " + pictureBean.isCut());
                Log.i(TAG, "原图地址: " + pictureBean.getPath());
                Log.i(TAG, "图片 Uri: " + pictureBean.getUri());
                if (pictureBean.isCut()) {
                    iv_far_pic.setImageBitmap(BitmapFactory.decodeFile(pictureBean.getPath()));
                } else {
                    if (ll_review.getVisibility() == View.VISIBLE) {
                        iv_review.setImageURI(pictureBean.getUri());
                    }
//                    iv_far_pic.setImageURI(pictureBean.getUri());
                    compressImage(pictureBean.getUri(),"far");
//                    far_pic_uri = pictureBean.getUri();
//                    far_pic_path = pictureBean.getPath();
//                    Glide.with(this)
//                            .load(pictureBean.getUri())
//                            .placeholder(R.drawable.ic_add_img)
//                            .error(R.drawable.ic_error_image)
//                            .into(iv_far_pic);
                }
            }
        } else if (requestCode == (0x02)) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                Log.i(TAG, "是否裁剪: " + pictureBean.isCut());
                Log.i(TAG, "原图地址: " + pictureBean.getPath());
                Log.i(TAG, "图片 Uri: " + pictureBean.getUri());
                if (pictureBean.isCut()) {
                    iv_near_pic.setImageBitmap(BitmapFactory.decodeFile(pictureBean.getPath()));
                } else {

                    if (ll_review.getVisibility() == View.VISIBLE) {
                        iv_review.setImageURI(pictureBean.getUri());
                    }
//                    iv_near_pic.setImageURI(pictureBean.getUri());
                    compressImage(pictureBean.getUri(),"near");

                }
            }
        } else if (requestCode == (0x03)) {
            if (data != null) {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                Log.i(TAG, "是否裁剪: " + pictureBean.isCut());
                Log.i(TAG, "原图地址: " + pictureBean.getPath());
                Log.i(TAG, "图片 Uri: " + pictureBean.getUri());
                if (pictureBean.isCut()) {
                    iv_pole_pic.setImageBitmap(BitmapFactory.decodeFile(pictureBean.getPath()));
                } else {

                    if (ll_review.getVisibility() == View.VISIBLE) {
                        iv_review.setImageURI(pictureBean.getUri());
                    }
//                    iv_pole_pic.setImageURI(pictureBean.getUri());
                    compressImage(pictureBean.getUri(),"pole");

                }

            }
        }
    }

    private void compressImage(Uri uri,String type)
    {
        ArrayList<CompressServiceParam> tasks = new ArrayList<CompressServiceParam>(1);
        CompressServiceParam param = new CompressServiceParam();
        param.setOutHeight(800);
        param.setOutWidth(600);
        param.setMaxFileSize(1024);
        param.setSrcImageUri(uri.toString());
        param.setType(type);
        LGImgCompressorIntentService.startActionCompress(PointDeviceActivity.this, param);
    }

    private class CompressingReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG, "onReceive:" + Thread.currentThread().getId());
            int flag = intent.getIntExtra(Constanse.KEY_COMPRESS_FLAG,-1);
            Log.e(TAG," flag:" + flag);
            if(flag == Constanse.FLAG_BEGAIIN){
                Log.e(TAG, "onCompressServiceStart");
                serviceStartTime = System.currentTimeMillis();
                //ToastUtils.toast(context,"compress begain...");
                return;
            }
            if(flag == Constanse.FLAG_END){
                ArrayList<LGImgCompressor.CompressResult> compressResults =
                        (ArrayList<LGImgCompressor.CompressResult>)intent.getSerializableExtra(Constanse.KEY_COMPRESS_RESULT);
                Log.e(TAG, compressResults.size() + "compressed done");
                for (LGImgCompressor.CompressResult  compressResult : compressResults)
                {
                    if (compressResult.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)
                    {
                        ToastUtils.toast(context,"压缩失败");
                    }
                    Log.e(TAG, compressResult.getType() +"++++++" + compressResult.getOutPath());
                    String type = compressResult.getType();
                    String path = compressResult.getOutPath();
                    if(path == null)
                    {
                        Log.e(TAG, "压缩失败");
                        return;
                    }
                    File file = new File(path);
                    if (!file.exists()){
                        return;
                    }
                    Uri uri =  Uri.fromFile(file);
                    if (type.equals("far"))
                    {
                        far_pic_uri = uri;
                        far_pic_path = path;
                        Glide.with(context)
                                    .load(uri)
                                    .placeholder(R.drawable.ic_add_img)
                                    .error(R.drawable.ic_error_image)
                                    .into(iv_far_pic);

                    }
                    else if (type.equals("near")){
                        near_pic_uri = uri;
                        near_pic_path = path;
                        Glide.with(context)
                                .load(uri)
                                .placeholder(R.drawable.ic_add_img)
                                .error(R.drawable.ic_error_image)
                                .into(iv_near_pic);
                    }
                    else if (type.equals("pole")){
                        pole_pic_uri = uri;
                        pole_pic_path = path;
                        Glide.with(context)
                                .load(uri)
                                .placeholder(R.drawable.ic_add_img)
                                .error(R.drawable.ic_error_image)
                                .into(iv_pole_pic);
                    }
                }
                Log.e(TAG, "compress " + compressResults.size() + " files used total time:" + (System.currentTimeMillis() - serviceStartTime));
                //ToastUtils.toast(context,compressResults.size() + " files compressed done \nused total time:" + (System.currentTimeMillis() - serviceStartTime) + "ms");
            }
        }
    }

    private void updatePolylineData(PolylineDeviceBean polyline) {
        daoSession.getPolylineDeviceBeanDao().update(polyline);
        Toast.makeText(this, "更新成功。。。。", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(reciver != null){
            unregisterReceiver(reciver);
        }
    }

    public void showTransformAlertDialog()
    {
        List<TransformerLibrary> transformerModelList =  daoSession.getTransformerLibraryDao().queryBuilder().list();
        ListView listView = new ListView(this);
        View view = LayoutInflater.from(this).inflate(R.layout.tranformer_dialog_header,null,false);
        listView.addHeaderView(view);
        ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
        for (int i = 0 ; i < transformerModelList.size();i++)
        {
            TransformerLibrary transformerLibrary = transformerModelList.get(i);
            HashMap<String,String> map = new HashMap<>();
            map.put("pole", transformerLibrary.getPoleModel());
            map.put("transformer", transformerLibrary.getTransformerModel());
            map.put("capacity", transformerLibrary.getCapacity());
            dataList.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, dataList, R.layout.transformer_dialog_item,
                new String[]{"pole", "transformer", "capacity"},
                new int[]{R.id.transformer_dialog_pole, R.id.transformer_dialog_trans, R.id.transformer_dialog_capacity}
        );
        listView.setAdapter(adapter);
        AlertDialog dialog = new  AlertDialog.Builder(this)
                .setView(listView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TransformerLibrary transformerLibrary = transformerModelList.get(position - 1);
                et_tower_model.setText(transformerLibrary.getTransformerModel());
                tr_trans_pole_model.setVisibility(View.VISIBLE);
                et_trans_pole_model.setText(transformerLibrary.getPoleModel());
                dialog.dismiss();
            }
        });
        dialog.show();
    }

}

